# -*- coding: utf-8 -*-
# @Time       : 2019/8/18 下午7:01
# @Author     : Simon
# @Email      :
# @File       : Test.py
# @Software   : PyCharm
# @Description:

import demjson
import emoji as emoji

from Redis.redis import RedisConnect
from db import Session, ShopMeituanInfo, datetime, MTSpider, Report, json, logger, traceback, getShopReportHeadInfo


def get_comment(shopId, shopType, cookies, startDay, endDay):
    if shopType == 1:
        commentList = []
        star = [0 for n in range(5)]
        mt = MTSpider(cookies)
        pageNum = 1
        commentCount = 1
        while True:

            res = mt.commentList(pageNum, startDay, endDay)
            comments = res.get("comments")
            if len(comments) == 0:
                break
            else:
                pageNum += 1
                for comment in comments:
                    clean_comment = comment.get("clean_comment")
                    add_comment = comment.get("add_comment")
                    starNum = comment.get("order_comment_score")
                    star[starNum - 1] += 1
                    if add_comment is None:
                        #将None转化为空字符串
                        add_comment = ''
                    if not clean_comment == '' or not add_comment == '':
                        #只要其中一个评论不为空
                        commentStr = str(commentCount) + "." + clean_comment + " " + add_comment
                        commentStr = emoji.demojize(commentStr)
                        commentList.append(commentStr)
                        commentCount += 1
        return {"commentList" : commentList, "star" : star}
def get_exposure_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.exposureInfo('1')
    flowExposureInfoList = res.get("flowExposureInfoList")
    # 01:商家列表； 02:搜索， 03:顾客订单页, 04:为你优选, 05:其他
    exposureInfoList = [0 for i in range(5)]
    peerExposureInfoList = [0 for i in range(5)]
    for flowExposureInfo in flowExposureInfoList:
        exposureInfoList[flowExposureInfo.get("entryId") - 1] = flowExposureInfo.get("exposureNum")
        peerExposureInfoList[flowExposureInfo.get("entryId") - 1] = flowExposureInfo.get("exposureNumTop")
    return {"exposureInfoList" : exposureInfoList, "peerExposureInfoList" : peerExposureInfoList }


def get_customer_info(shopId, shopType, cookies, startDay, endDay):
    mt = MTSpider(cookies)
    res = mt.customerManageV3NewOldView(1, startDay, endDay)
    newOldInfoList = []
    if res:

        newOldListIterator = res.get("newOldListIterator")
        for newOldInfo in newOldListIterator:
            dataDate = newOldInfo.get("dataDate")
            dataDate = dataDate[:4] + "-" + dataDate[4:6] + "-" + dataDate[6:]
            newSingle = newOldInfo.get("newSingle")
            oldSingle = newOldInfo.get("oldSingle")
            newPercent = newOldInfo.get("newPercent")
            oldPercent = newOldInfo.get("oldPercent")
            newOldInfoList.append({"dataDate" : dataDate, "newSingle" : newSingle, "oldSingle" : oldSingle, "newPercent" : newPercent, "oldPercent": oldPercent})
        return newOldInfoList
    else:
        newOldInfoList.append(
            {"dataDate": '', "newSingle": -1, "oldSingle": -1, "newPercent": -1,
             "oldPercent": -1})
        return newOldInfoList

def get_comment_summary(shopId, shopType, cookies):
    # 获取评分的接口
    mt = MTSpider(cookies)
    res = mt.commentSummary()
    bizScore = res.get("bizScore")
    return bizScore

def get_activity(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    activityList = []
    res = mt.getActivity("1,8", 1, 10)
    list = res.get("list")
    '''
        折扣商品: type:17
        满减：type:2
        店外领券：type:84
        减配送费: type: 25
        ...
    '''
    for activity in list:

        activityList.append({"name": activity.get("name"), "detail" : activity.get("detail"), "startTime":activity.get("startTime"), "endTime" : activity.get("endTime")})

    return activityList

def get_shop_rank(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getShopRank()

    rankNum = res[0].get("rankNum")
    score = res[0].get("score")
    cityName = res[0].get("cityName")

    return {"rankNum" : rankNum, "score" : score, "cityName" : cityName}



def get_over_view(shopId, shopType, cookies, day):
    mt = MTSpider(cookies)
    res = mt.getHisOverView(day, day)
    settleAcc = res.get("settleAcc")
    effectiveOrders = res.get("effectiveOrders")
    return {"settleAcc": settleAcc, "effectiveOrders": effectiveOrders}

def customerManageV3(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.customerManageV3(2, '20190916' , '20191215')

    if res:
        allRepeat = res.get("allRepeat")
        allRepeatRate = res.get("allRepeatRate")
        allRepeatCompareLastWeek = res.get("allRepeatSequential")
        allRepeatCompareLastMonth = res.get("allRepeatCompareSame")

        newRepeat = res.get("newRepeat")
        newRepeatRate = res.get("newRepeatRate")
        newRepeatCompareLastWeek = res.get("newRepeatSequential")
        newRepeatCompareLastMonth = res.get("newRepeatCompareSame")

        oldRepeat = res.get("oldRepeat")
        oldRepeatRate = res.get("oldRepeatRate")
        oldRepeatCompareLastWeek = res.get("oldRepeatSequential")
        oldRepeatCompareLastMonth = res.get("oldRepeatCompareSame")

        return dict(
            allRepeat = allRepeat,
            allRepeatRate = allRepeatRate,
            allRepeatCompareLastWeek = allRepeatCompareLastWeek,
            allRepeatCompareLastMonth = allRepeatCompareLastMonth,
            newRepeat = newRepeat,
            newRepeatRate = newRepeatRate,
            newRepeatCompareLastWeek = newRepeatCompareLastWeek,
            newRepeatCompareLastMonth = newRepeatCompareLastMonth,
            oldRepeat = oldRepeat,
            oldRepeatRate = oldRepeatRate,
            oldRepeatCompareLastWeek = oldRepeatCompareLastWeek,
            oldRepeatCompareLastMonth = oldRepeatCompareLastMonth,
        )
    else:
        return dict(
            allRepeat=None,
            allRepeatRate=None,
            allRepeatCompareLastWeek=None,
            allRepeatCompareLastMonth=None,
            newRepeat=None,
            newRepeatRate=None,
            newRepeatCompareLastWeek=None,
            newRepeatCompareLastMonth=None,
            oldRepeat=None,
            oldRepeatRate=None,
            oldRepeatCompareLastWeek=None,
            oldRepeatCompareLastMonth=None,
        )

def get_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("1","1")
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    exposureNum = flowChartsInfoList[-1].get("exposureNumLast")
    visitNum = flowChartsInfoList[-1].get("visitNumLast")
    orderNum = flowChartsInfoList[-1].get("orderNumLast")
    visitRate = flowChartsInfoList[-1].get("visitRateLast")
    orderRate = flowChartsInfoList[-1].get("orderRateLast")
    return {"exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate}

def get_days_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("7","1")
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    exposureNum = flowChartsInfoList[-1].get("exposureNum")
    visitNum = flowChartsInfoList[-1].get("visitNum")
    orderNum = flowChartsInfoList[-1].get("orderNum")
    visitRate = flowChartsInfoList[-1].get("visitRate")
    orderRate = flowChartsInfoList[-1].get("orderRate")
    return {"exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate}

def get_peer_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getOverView()
    flowOverviewInfo = res.get("data").get("flowOverviewInfo")
    peerExposureNum = flowOverviewInfo.get("exposureNumTop")
    peerVisitRate = flowOverviewInfo.get("visitRateTop")
    peerOrderRate = flowOverviewInfo.get("orderRateTop")
    return {"peerExposureNum" : peerExposureNum, "peerVisitRate" : peerVisitRate ,"peerOrderRate" : peerOrderRate}


def get_7days_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("7","1")
    trendInfoList = []
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    for flowChartsInfo in flowChartsInfoList:
        exposureNum = flowChartsInfo.get("exposureNum")
        visitNum = flowChartsInfo.get("visitNum")
        orderNum = flowChartsInfo.get("orderNum")
        visitRate = flowChartsInfo.get("visitRate")
        orderRate = flowChartsInfo.get("orderRate")
        date = flowChartsInfo.get("date")
        peerExposureNum = flowChartsInfo.get("exposureNumTop")
        peerVisitRate = flowChartsInfo.get("visitRateTop")
        peerOrderRate = flowChartsInfo.get("orderRateTop")
        trendInfoList.append({"date" : date,"peerExposureNum":peerExposureNum,"peerVisitRate":peerVisitRate,"peerOrderRate":peerOrderRate,  "exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate})
    return trendInfoList


def get_yes_cpc_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    cpcInfo = mt.gettodayExposure()
    cost = cpcInfo.get("data").get("yesterdayOverview").get("cost")
    return cost



def getAllShopLastDayReportData(shopId):
    session = Session()
    shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    shopName = shop.mtName
    try:
        cookies = shop.cookies
        shopId = shop.mtId
        k = 1
        day2 = (datetime.datetime.now() + datetime.timedelta(days = -1 * k )).strftime("%Y-%m-%d")
        endDay = day2.replace("-", '')
        repeatInfo = customerManageV3(shopId, 1, cookies)
        newOldInfo = get_customer_info(shopId, 1, cookies, endDay, endDay)[0]

        trendInfo = get_days_trend_info(shopId, 1, cookies)
        activityList = get_activity(shopId, 1, cookies)
        activityList = json.dumps(activityList, ensure_ascii=False)

        allRepeat = repeatInfo.get("allRepeat")
        allRepeatRate = repeatInfo.get("allRepeatRate")
        allRepeatCompareLastWeek = repeatInfo.get("allRepeatCompareLastWeek")
        allRepeatCompareLastMonth = repeatInfo.get("allRepeatCompareLastMonth")
        newRepeat = repeatInfo.get("newRepeat")
        newRepeatRate = repeatInfo.get("newRepeatRate")
        newRepeatCompareLastWeek = repeatInfo.get("newRepeatCompareLastWeek")
        newRepeatCompareLastMonth = repeatInfo.get("newRepeatCompareLastMonth")
        oldRepeat = repeatInfo.get("oldRepeat")
        oldRepeatRate = repeatInfo.get("oldRepeatRate")
        oldRepeatCompareLastWeek = repeatInfo.get("oldRepeatCompareLastWeek")
        oldRepeatCompareLastMonth = repeatInfo.get("oldRepeatCompareLastMonth")

        peerTrendInfo = get_peer_trend_info(shopId, 1, cookies)
        peerExposureNum = peerTrendInfo.get("peerExposureNum")
        peerVisitRate = peerTrendInfo.get("peerVisitRate")
        peerOrderRate = peerTrendInfo.get("peerOrderRate")

        overViewInfo = get_over_view(shopId, 1, cookies, endDay)
        cost = get_yes_cpc_info(shopId, 1, cookies)
        commentResult = get_comment(shopId, 1, cookies, day2, day2)
        commentList = commentResult.get("commentList")
        commentList = json.dumps(commentList, ensure_ascii = False)
        star = commentResult.get("star")
        star = json.dumps(star, ensure_ascii = False)
        exposureInfo = get_exposure_info(shopId, 1, cookies).get("exposureInfoList")
        bizListExposureNum = exposureInfo[0]
        searchExposureNum = exposureInfo[1]
        orderPageExposureNum = exposureInfo[2]
        selectForUExposureNum = exposureInfo[3]
        otherExposureNum = exposureInfo[4]
        peerExposureInfoList = get_exposure_info(shopId, 1, cookies).get("peerExposureInfoList")
        peerBizListExposureNum = peerExposureInfoList[0]
        peerSearchExposureNum = peerExposureInfoList[1]
        peerOrderPageExposureNum = peerExposureInfoList[2]
        peerSelectForUExposureNum = peerExposureInfoList[3]
        peerOtherExposureNum = peerExposureInfoList[4]

        score = get_comment_summary(shopId, 1, cookies)

        rank = get_shop_rank(shopId, 1, cookies)
        rankNum = rank.get("rankNum")
        if not k == 1:
            bizListExposureNum = -1
            searchExposureNum = -1
            orderPageExposureNum = -1
            selectForUExposureNum = -1
            otherExposureNum = -1
            peerExposureNum = -1
            peerVisitRate = -1
            peerOrderRate = -1
            peerBizListExposureNum = -1
            peerSearchExposureNum = -1
            peerOrderPageExposureNum = -1
            peerSelectForUExposureNum = -1
            peerOtherExposureNum = -1
            cost = -1
        report = session.query(Report).filter(Report.date == day2, Report.shopId == shopId).first()
        if not report:
            session.add(Report(
                shopId = shopId,
                shopType = 1,
                date = day2,
                comment = commentList,
                bizListExposureNum = bizListExposureNum,
                searchExposureNum = searchExposureNum,
                orderPageExposureNum = orderPageExposureNum,
                selectForUExposureNum = selectForUExposureNum,
                otherExposureNum = otherExposureNum,
                peerBizListExposureNum = peerBizListExposureNum,
                peerSearchExposureNum = peerSearchExposureNum,
                peerOrderPageExposureNum = peerOrderPageExposureNum,
                peerSelectForUExposureNum = peerSelectForUExposureNum,
                peerOtherExposureNum = peerOtherExposureNum,
                peerExposureNum = peerExposureNum,
                peerVisitRate = peerVisitRate,
                peerOrderRate = peerOrderRate,
                newSingle = newOldInfo.get("newSingle"),
                oldSingle = newOldInfo.get("oldSingle"),
                newPercent = newOldInfo.get("newPercent"),
                oldPercent = newOldInfo.get("oldPercent"),
                score = score,
                activity = activityList,
                exposureNum = trendInfo.get("exposureNum"),
                visitNum = trendInfo.get("visitNum"),
                orderNum = trendInfo.get("orderNum"),
                visitRate = trendInfo.get("visitRate"),
                orderRate = trendInfo.get("orderRate"),
                cost = cost,
                settleAcc = overViewInfo.get("settleAcc"),
                effectiveOrders = overViewInfo.get("effectiveOrders"),
                commentStarInfo = star,
                allRepeat=allRepeat,
                allRepeatRate=allRepeatRate,
                allRepeatCompareLastWeek=allRepeatCompareLastWeek,
                allRepeatCompareLastMonth=allRepeatCompareLastMonth,
                newRepeat=newRepeat,
                newRepeatRate=newRepeatRate,
                newRepeatCompareLastWeek=newRepeatCompareLastWeek,
                newRepeatCompareLastMonth=newRepeatCompareLastMonth,
                oldRepeat=oldRepeat,
                oldRepeatRate=oldRepeatRate,
                oldRepeatCompareLastWeek=oldRepeatCompareLastWeek,
                oldRepeatCompareLastMonth=oldRepeatCompareLastMonth,
            ))
        else:
            # 更新
            report.comment = commentList
            report.bizListExposureNum = bizListExposureNum
            report.searchExposureNum = searchExposureNum
            report.orderPageExposureNum = orderPageExposureNum
            report.selectForUExposureNum = selectForUExposureNum
            report.otherExposureNum = otherExposureNum
            report.newSingle = newOldInfo.get("newSingle")
            report.oldSingle = newOldInfo.get("oldSingle")
            report.newPercent = newOldInfo.get("newPercent")
            report.oldPercent = newOldInfo.get("oldPercent")
            report.score = score
            report.activity = activityList
            report.exposureNum = trendInfo.get("exposureNum")
            report.visitNum = trendInfo.get("visitNum")
            report.orderNum = trendInfo.get("orderNum")
            report.visitRate = trendInfo.get("visitRate")
            report.orderRate = trendInfo.get("orderRate")
            report.cost = cost
            report.settleAcc = overViewInfo.get("settleAcc")
            report.effectiveOrders = overViewInfo.get("effectiveOrders")
            report.commentStarInfo = star
            report.peerBizListExposureNum = peerBizListExposureNum
            report.peerSearchExposureNum = peerSearchExposureNum
            report.peerOrderPageExposureNum = peerOrderPageExposureNum
            report.peerSelectForUExposureNum = peerSelectForUExposureNum
            report.peerOtherExposureNum = peerOtherExposureNum
            report.peerExposureNum = peerExposureNum
            report.peerVisitRate = peerVisitRate
            report.peerOrderRate = peerOrderRate
            report.allRepeat = allRepeat
            report.allRepeatRate = allRepeatRate
            report.allRepeatCompareLastWeek = allRepeatCompareLastWeek
            report.allRepeatCompareLastMonth = allRepeatCompareLastMonth
            report.newRepeat = newRepeat
            report.newRepeatRate = newRepeatRate
            report.newRepeatCompareLastWeek = newRepeatCompareLastWeek
            report.newRepeatCompareLastMonth = newRepeatCompareLastMonth
            report.oldRepeat = oldRepeat
            report.oldRepeatRate = oldRepeatRate
            report.oldRepeatCompareLastWeek = oldRepeatCompareLastWeek
            report.oldRepeatCompareLastMonth = oldRepeatCompareLastMonth
    except:
        print("{}：数据获取失败 =_=  =_=".format(shopName))
        logger.info(traceback.format_exc())

    session.commit()
    session.close()




